/*
 *  Copyright (C) 2009 takaji
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * AccountManagerView.java
 *
 * Created on Dec 22, 2009, 11:31:29 PM
 */
package dakside.hacc.modules.accounting.accounttree;

import dakside.hacc.core.models.Account;
import java.awt.Component;
import java.awt.event.KeyEvent;
import javax.swing.tree.TreePath;
import org.dakside.duck.plugins.AppConstants;
import org.dakside.duck.plugins.Command;
import org.dakside.duck.plugins.DefaultCommandInvoker;
import org.dakside.duck.plugins.ToolbarContainer;

/**
 *
 * @author Takaji
 */
public class AccountManagerView extends javax.swing.JPanel implements ToolbarContainer {

    /** Creates new form AccountManagerView */
    public AccountManagerView() {
        initComponents();
        loadAccountTreeFromDatabase();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        customToolbar = new javax.swing.JToolBar();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        accountDetailPanel1 = new dakside.hacc.modules.accounting.accounttree.AccountDetailPanel();
        btnSave = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        accountTree1 = new dakside.hacc.modules.accounting.accounttree.AccountTree();

        customToolbar.setFloatable(false);
        customToolbar.setRollover(true);

        jSplitPane1.setDividerLocation(200);

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(accountDetailPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnSave)
                .addContainerGap(274, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(accountDetailPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSave)
                .addContainerGap(164, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Accounts");
        accountTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        accountTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                accountTree1ValueChanged(evt);
            }
        });
        accountTree1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                accountTree1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(accountTree1);

        jSplitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        //get account details from detailPanel
        Account acc = accountDetailPanel1.getAccount();
        //add to tree
        accountTree1.addAccount(acc, accountTree1.getSelectionPath());
    }//GEN-LAST:event_btnSaveActionPerformed

    private void accountTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_accountTree1ValueChanged
        TreePath path = evt.getNewLeadSelectionPath();
        Account acc = accountTree1.getAccountFromPath(path);
        updateAccountDetailsPanel(acc);
    }

    private void updateAccountDetailsPanel(Account acc) {
        accountDetailPanel1.setAccount(acc);
        //an account is selected
        if (acc != null) {
            //button state
            boolean canInsert = acc != null && acc.getType() == Account.TYPE_FOLDER;
            getInvoker().setEnabled(AppConstants.Commands.NEW, canInsert);
            boolean canChangeAccount = AccountManager.getInstance().canDelete(acc);
            getInvoker().setEnabled(AppConstants.Commands.DELETE, canChangeAccount);
            accountDetailPanel1.setState(canChangeAccount);
        }
    }//GEN-LAST:event_accountTree1ValueChanged

    private void accountTree1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_accountTree1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_INSERT) {
            insertSelection();
        } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
            deleteSelection();
        }
    }//GEN-LAST:event_accountTree1KeyPressed

    private final void save() {
        Account root = accountTree1.toAccountTree();
        AccountManager.getInstance().save(root);
        Account[] acc = AccountManager.getInstance().getAllAccounts();
    }

    /**
     * Insert a new account at selection path
     */
    private void insertSelection() {
        accountTree1.insertAccountAtSelection();
    }

    /**
     * Delete selection accounts
     */
    private void deleteSelection() {
        Account[] accounts = accountTree1.removeAccountAtSelection();
        //AccountManager.getInstance().delete(accounts);
    }

    /**
     * Load account tree from database
     */
    private void loadAccountTreeFromDatabase() {
        Account root = AccountManager.getInstance().getAccountTree();
        accountTree1.loadTree(root);
        accountDetailPanel1.setAccount(root);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dakside.hacc.modules.accounting.accounttree.AccountDetailPanel accountDetailPanel1;
    private dakside.hacc.modules.accounting.accounttree.AccountTree accountTree1;
    private javax.swing.JButton btnSave;
    private javax.swing.JToolBar customToolbar;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration//GEN-END:variables
    //TOOLBAR CONTAINER SUPPORT
    private Component[] toolbar;

    public Component[] getToolbarItems() {
        if (toolbar == null) {
            toolbar = customToolbar.getComponents();
        }
        return toolbar;
    }
    private DefaultCommandInvoker myInvoker = null;

    public final synchronized DefaultCommandInvoker getInvoker() {
        if (myInvoker == null) {
            myInvoker = new DefaultCommandInvoker();
            myInvoker.add(AppConstants.Commands.SAVE, new Command() {

                public Object invoke(Object[] args) {
                    save();
                    return true;
                }
            });
            myInvoker.add(AppConstants.Commands.REFRESH, new Command() {

                public Object invoke(Object[] args) {
                    loadAccountTreeFromDatabase();
                    return true;
                }
            });

            myInvoker.add(AppConstants.Commands.DELETE, new Command() {

                public Object invoke(Object[] args) {
                    deleteSelection();
                    return true;
                }
            });
            myInvoker.add(AppConstants.Commands.NEW, new Command() {

                public Object invoke(Object[] args) {
                    insertSelection();
                    return true;
                }
            });
        }
        return myInvoker;
    }
    //END OF TOOLBAR CONTAINER SUPPORT
}
